<template>
  <div class="paper-create-container">
    <div class="page-header">
      <h2>创建试卷</h2>
      <div>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="paper-form"
    >
      <el-card class="form-card">
        <template #header>
          <span>基本信息</span>
        </template>
        
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入试卷名称" />
        </el-form-item>
        
        <el-form-item label="试卷描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入试卷描述"
          />
        </el-form-item>
        
        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="form.duration"
            :min="1"
            :max="300"
            controls-position="right"
          />
          <span class="unit">分钟</span>
        </el-form-item>
        
        <el-form-item label="总分" prop="totalScore">
          <el-input-number
            v-model="form.totalScore"
            :min="1"
            :max="1000"
            controls-position="right"
          />
          <span class="unit">分</span>
        </el-form-item>
        
        <el-form-item label="及格分数" prop="passScore">
          <el-input-number
            v-model="form.passScore"
            :min="1"
            :max="form.totalScore"
            controls-position="right"
          />
          <span class="unit">分</span>
        </el-form-item>
      </el-card>

      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>题目设置</span>
            <el-button type="primary" size="small" @click="handleAddQuestion">
              <el-icon><Plus /></el-icon>
              添加题目
            </el-button>
          </div>
        </template>
        
        <div v-if="form.questions.length === 0" class="empty-questions">
          <el-empty description="暂无题目，请添加题目" />
        </div>
        
        <div v-else class="questions-list">
          <div
            v-for="(question, index) in form.questions"
            :key="question.id"
            class="question-item"
          >
            <div class="question-header">
              <span class="question-number">题目 {{ index + 1 }}</span>
              <div class="question-actions">
                <el-button size="small" @click="handleEditQuestion(question, index)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleRemoveQuestion(index)">删除</el-button>
              </div>
            </div>
            <div class="question-content">
              <div class="question-title">{{ question.title }}</div>
              <div class="question-meta">
                <el-tag size="small">{{ getQuestionTypeText(question.type) }}</el-tag>
                <span class="score">{{ question.score }}分</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </el-form>

    <!-- 添加/编辑题目对话框 -->
    <el-dialog
      v-model="questionDialogVisible"
      :title="questionDialogTitle"
      width="60%"
      @close="handleCloseQuestionDialog"
    >
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="questionRules"
        label-width="100px"
      >
        <el-form-item label="题目类型" prop="type">
          <el-select v-model="questionForm.type" placeholder="请选择题目类型">
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="judge" />
            <el-option label="填空题" value="fill" />
            <el-option label="简答题" value="essay" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="题目标题" prop="title">
          <el-input
            v-model="questionForm.title"
            type="textarea"
            :rows="3"
            placeholder="请输入题目标题"
          />
        </el-form-item>
        
        <el-form-item label="分值" prop="score">
          <el-input-number
            v-model="questionForm.score"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="questionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveQuestion">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const saving = ref(false)
const formRef = ref()
const questionFormRef = ref()

const form = reactive({
  name: '',
  description: '',
  duration: 60,
  totalScore: 100,
  passScore: 60,
  questions: []
})

const rules = {
  name: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入试卷描述', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' }
  ],
  totalScore: [
    { required: true, message: '请输入总分', trigger: 'blur' }
  ],
  passScore: [
    { required: true, message: '请输入及格分数', trigger: 'blur' }
  ]
}

// 题目对话框
const questionDialogVisible = ref(false)
const questionDialogTitle = computed(() => {
  return editingQuestionIndex.value >= 0 ? '编辑题目' : '添加题目'
})
const editingQuestionIndex = ref(-1)

const questionForm = reactive({
  type: '',
  title: '',
  score: 5
})

const questionRules = {
  type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入题目标题', trigger: 'blur' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' }
  ]
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const types = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return types[type] || '未知'
}

// 添加题目
const handleAddQuestion = () => {
  editingQuestionIndex.value = -1
  Object.assign(questionForm, {
    type: '',
    title: '',
    score: 5
  })
  questionDialogVisible.value = true
}

// 编辑题目
const handleEditQuestion = (question, index) => {
  editingQuestionIndex.value = index
  Object.assign(questionForm, {
    type: question.type,
    title: question.title,
    score: question.score
  })
  questionDialogVisible.value = true
}

// 删除题目
const handleRemoveQuestion = async (index) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这道题目吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    form.questions.splice(index, 1)
    ElMessage.success('删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

// 保存题目
const handleSaveQuestion = async () => {
  try {
    await questionFormRef.value.validate()
    
    const questionData = {
      id: Date.now(),
      type: questionForm.type,
      title: questionForm.title,
      score: questionForm.score
    }
    
    if (editingQuestionIndex.value >= 0) {
      // 编辑模式
      form.questions[editingQuestionIndex.value] = questionData
      ElMessage.success('题目更新成功')
    } else {
      // 添加模式
      form.questions.push(questionData)
      ElMessage.success('题目添加成功')
    }
    
    questionDialogVisible.value = false
  } catch (error) {
    // 验证失败
  }
}

// 关闭题目对话框
const handleCloseQuestionDialog = () => {
  questionFormRef.value?.resetFields()
}

// 保存试卷
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    if (form.questions.length === 0) {
      ElMessage.warning('请至少添加一道题目')
      return
    }
    
    saving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('试卷创建成功')
    router.push('/papers')
  } catch (error) {
    if (error !== 'validation failed') {
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    saving.value = false
  }
}

// 取消
const handleCancel = () => {
  router.back()
}
</script>

<style scoped>
.paper-create-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.paper-form {
  max-width: 800px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.unit {
  margin-left: 8px;
  color: #909399;
}

.empty-questions {
  text-align: center;
  padding: 40px 0;
}

.questions-list {
  space-y: 16px;
}

.question-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-number {
  font-weight: 500;
  color: #303133;
}

.question-content {
  padding-left: 16px;
}

.question-title {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.5;
}

.question-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.score {
  color: #409eff;
  font-weight: 500;
}
</style>